<template>
  <div class="mock-data-container">
    <a-card class="header-card">
      <a-row :gutter="20">
        <a-col :span="12">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索接口或Mock规则"
            style="width: 300px"
            @search="onSearch"
          />
        </a-col>
        <a-col :span="12" class="text-right">
          <a-button type="primary" @click="showCreateModal">
            <PlusOutlined />
            添加Mock规则
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <a-card class="content-card">
      <a-table
        :data-source="mockDataList"
        :columns="columns"
        :pagination="pagination"
        @change="handleTableChange"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'method'">
            <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="editMockData(record)">编辑</a-button>
              <a-button type="link" @click="deleteMockData(record)">删除</a-button>
              <a-button type="link" @click="toggleStatus(record)">
                {{ record.status === 1 ? '禁用' : '启用' }}
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑Mock规则 Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="editingMockData ? '编辑Mock规则' : '添加Mock规则'"
      width="800px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item label="接口路径" required>
              <a-input v-model:value="form.path" placeholder="请输入接口路径" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="请求方法" required>
              <a-select v-model:value="form.method" placeholder="请选择请求方法">
                <a-select-option value="GET">GET</a-select-option>
                <a-select-option value="POST">POST</a-select-option>
                <a-select-option value="PUT">PUT</a-select-option>
                <a-select-option value="DELETE">DELETE</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="匹配规则">
          <a-textarea
            v-model:value="form.matchRule"
            placeholder="请输入匹配规则（JSON格式）"
            :rows="4"
          />
        </a-form-item>
        <a-form-item label="Mock数据">
          <a-tabs v-model:activeKey="dataTab">
            <a-tab-pane key="1" tab="JSON编辑器">
              <a-textarea
                v-model:value="form.mockData"
                placeholder="请输入Mock数据（JSON格式）"
                :rows="6"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="可视化编辑">
              <div class="visual-editor">
                <p>可视化编辑器功能（可在此添加拖拽式表单构建器）</p>
                <a-button @click="addMockField">添加字段</a-button>
                <div v-for="(field, index) in mockFields" :key="index" class="field-item">
                  <a-row :gutter="10">
                    <a-col :span="8">
                      <a-input v-model:value="field.key" placeholder="字段名" />
                    </a-col>
                    <a-col :span="8">
                      <a-select v-model:value="field.type" placeholder="字段类型">
                        <a-select-option value="string">字符串</a-select-option>
                        <a-select-option value="number">数字</a-select-option>
                        <a-select-option value="boolean">布尔值</a-select-option>
                        <a-select-option value="array">数组</a-select-option>
                        <a-select-option value="object">对象</a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="6">
                      <a-input v-model:value="field.value" placeholder="字段值" />
                    </a-col>
                    <a-col :span="2">
                      <a-button type="link" @click="removeMockField(index)">删除</a-button>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-form-item>
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item label="延迟时间(ms)">
              <a-input-number v-model:value="form.delay" :min="0" :max="10000" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态">
              <a-switch
                v-model:checked="form.status"
                checked-children="启用"
                un-checked-children="禁用"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default {
  name: 'MockData',
  components: {
    PlusOutlined
  },
  data() {
    return {
      searchText: '',
      loading: false,
      modalVisible: false,
      dataTab: '1',
      editingMockData: null,
      form: {
        path: '',
        method: 'GET',
        matchRule: '',
        mockData: '{\n  "code": 200,\n  "message": "success",\n  "data": []\n}',
        delay: 0,
        status: true
      },
      mockFields: [],
      mockDataList: [
        {
          id: 1,
          path: '/api/users',
          method: 'GET',
          matchRule: '{}',
          mockData: '{\n  "code": 200,\n  "message": "success",\n  "data": [\n    {\n      "id": 1,\n      "name": "张三"\n    }\n  ]\n}',
          delay: 0,
          status: 1,
          createTime: '2023-09-01 10:00:00'
        },
        {
          id: 2,
          path: '/api/users',
          method: 'POST',
          matchRule: '{}',
          mockData: '{\n  "code": 201,\n  "message": "created",\n  "data": {\n    "id": 1001\n  }\n}',
          delay: 100,
          status: 1,
          createTime: '2023-09-01 10:05:00'
        }
      ],
      columns: [
        {
          title: '接口路径',
          dataIndex: 'path',
          key: 'path'
        },
        {
          title: '请求方法',
          dataIndex: 'method',
          key: 'method'
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status'
        },
        {
          title: '延迟时间(ms)',
          dataIndex: 'delay',
          key: 'delay'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action'
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 2
      }
    };
  },
  methods: {
    onSearch() {
      message.success('搜索功能已触发');
    },
    showCreateModal() {
      this.editingMockData = null;
      this.form = {
        path: '',
        method: 'GET',
        matchRule: '',
        mockData: '{\n  "code": 200,\n  "message": "success",\n  "data": []\n}',
        delay: 0,
        status: true
      };
      this.mockFields = [];
      this.modalVisible = true;
    },
    editMockData(record) {
      this.editingMockData = record;
      this.form = { ...record };
      this.form.status = record.status === 1;
      this.mockFields = [];
      this.modalVisible = true;
    },
    deleteMockData(record) {
      const that = this;
      this.$confirm({
        title: '确认删除',
        content: `确定要删除Mock规则 "${record.path} ${record.method}" 吗？`,
        onOk() {
          // 模拟删除操作
          message.success('删除成功');
          that.mockDataList = that.mockDataList.filter(item => item.id !== record.id);
        }
      });
    },
    toggleStatus(record) {
      const index = this.mockDataList.findIndex(item => item.id === record.id);
      this.mockDataList[index].status = record.status === 1 ? 0 : 1;
      message.success(`${record.status === 1 ? '禁用' : '启用'}成功`);
    },
    handleModalOk() {
      if (!this.form.path || !this.form.method) {
        message.warning('请填写必填项');
        return;
      }

      if (this.editingMockData) {
        // 编辑操作
        const index = this.mockDataList.findIndex(item => item.id === this.editingMockData.id);
        this.mockDataList[index] = {
          ...this.form,
          id: this.editingMockData.id,
          status: this.form.status ? 1 : 0,
          createTime: this.editingMockData.createTime
        };
        message.success('编辑成功');
      } else {
        // 新增操作
        this.mockDataList.push({
          ...this.form,
          id: this.mockDataList.length + 1,
          status: this.form.status ? 1 : 0,
          createTime: new Date().toLocaleString()
        });
        message.success('新增成功');
      }
      this.modalVisible = false;
    },
    handleModalCancel() {
      this.modalVisible = false;
    },
    handleTableChange(pagination) {
      this.pagination = { ...pagination };
    },
    getMethodColor(method) {
      const colorMap = {
        GET: 'blue',
        POST: 'green',
        PUT: 'orange',
        DELETE: 'red'
      };
      return colorMap[method] || 'default';
    },
    addMockField() {
      this.mockFields.push({
        key: '',
        type: 'string',
        value: ''
      });
    },
    removeMockField(index) {
      this.mockFields.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.mock-data-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.content-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}

.field-item {
  margin-top: 10px;
}

.visual-editor {
  padding: 15px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  margin-bottom: 15px;
}
</style>